import {Injectable} from '@angular/core';
import {Http, Response, Headers, RequestOptions, URLSearchParams} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import {ApprInfo} from "./appr-info.class";
import {CerReissueAppr} from "./cert-reissue-appr.class";


@Injectable()
export class CertReissueApprService {

  constructor(private _http: Http) {
  }

  submitAppr(url: string, apprInfo: ApprInfo): Promise<any> {
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});

    return this._http.post(url, JSON.stringify(apprInfo), options)
      .toPromise()
      .then(this.extractData)
      .catch(this.handleError);
  }


  reviewAppr(url: string, pkid: string): Promise<any> {
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});

    return this._http.post(url, JSON.stringify({'pkid': pkid}), options).toPromise()
      .then(this.extractData)
      .catch(this.handleError);
  }

  deleteAppr(url: string, pkids: any[]): Promise<any> {
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});

    return this._http.post(url, JSON.stringify({'pkids': pkids}), options).toPromise()
      .then(this.extractData)
      .catch(this.handleError);
  }


  extractData(res: Response) {
    let body = res.json();
    return body || {};
  }

  handleError(error: Response | any) {
    let errMsg: string;

    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.description || JSON.stringify(body);
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    return Promise.reject(errMsg);
  }
}
